<template>
  <div class="h-full w-full flex flex-col justify-between">
    <div class="form pt-[15px] border-bottom">
      <el-form>
        <el-row :gutter="12">
          <el-col :span="3">
            <el-form-item>
              <el-input v-model="form.name" placeholder="用户名/昵称/备注" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <div class="w-full flex justify-between">
                <el-date-picker
                  v-model="form.date"
                  type="daterange"
                  unlink-panels
                  range-separator="－"
                  start-placeholder="选择开始时间"
                  end-placeholder="选择结束时间"
                  :disabled-date="disableFutureDates"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="15">
            <el-form-item>
              <el-button type="primary" @click.stop="search">搜索</el-button>
              <el-button type="danger" @click.stop="handleRefresh">清空</el-button>
              <el-button type="danger" v-if="premsStore.isEditDeleteReport" @click.stop="handleDel">
                删除
              </el-button>
              <el-button type="danger" @click.stop="handleBarch">批量返佣</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="grow-[1] h-0">
      <el-table
        scrollbar-always-on
        ref="elTableRef"
        v-loading="state.loading"
        :data="list"
        style="width: 100%"
        height="100%"
        border
        stripe
        fit
      >
        <template #empty>
          <ui-empty />
        </template>
        <el-table-column
          align="center"
          prop="Name"
          label="用户名"
          show-overflow-tooltip
          width="90"
        />
        <el-table-column align="center" prop="Nickname" label="昵称" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Nickname || "--" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Level" label="代理等级" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Level + "级代理" || "--" }}
          </template>
        </el-table-column>
        <el-table-column align="center" prop="Note" label="备注" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Note || "--" }}
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="BetAmount"
          label="旗下流水"
          show-overflow-tooltip
          min-width="120"
        >
          <template #default="{ row }: TableItem">
            <ui-amount :num="row.BetAmount"></ui-amount>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="RebateAmount"
          label="总佣金"
          show-overflow-tooltip
          min-width="120"
        >
          <template #default="{ row }: TableItem">
            <ui-amount :num="row.RebateAmount"></ui-amount>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="RebateAmountNo"
          label="未返佣"
          show-overflow-tooltip
          min-width="120"
        >
          <template #default="{ row }: TableItem">
            <ui-amount :num="row.RebateAmountNo"></ui-amount>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="{ row }: TableItem">
            <el-button type="primary" size="small" @click.stop="handleOpenDetail(row)">
              旗下详情
            </el-button>
            <el-button
              v-if="premsStore.isEditAgentSetting"
              type="success"
              size="small"
              @click.stop="handleAction(row, 1)"
            >
              一键返佣
            </el-button>
            <!-- <el-button type="danger" size="small" @click.stop="handleAction(row, 2)">
              拒绝
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="flex justify-between my-[10px]">
      <div class="flex-1 w-0 mr-[20px]">
        <el-alert
          title="注意：返佣报表中的旗下流水，是按操作返佣当时的时间统计。比如昨天有500流水没有返佣，在今天操作了返佣，那昨天的流水在返佣报表中是统计在今天。报表最多保留两月数据。"
          type="warning"
          show-icon
          :closable="false"
        />
      </div>
      <ui-pagination
        :total="state.total"
        v-model:pageSize="state.pageSize"
        v-model:currentPage="state.page"
        @current-change="getData"
      ></ui-pagination>
    </div>
    <!-- 详情 -->
    <agent-rebate-detail-dialog
      ref="rebateDetailDialogRef"
      :uid="currentData?.UserId"
      :name="currentData?.Name"
      :date="form.date"
    />
    <DeleteDialog ref="deleteDialogRef" />
  </div>
</template>
<script setup lang="ts">
import AgentRebateDetailDialog from "./agent-rebate-detail-dialog.vue";
import DeleteDialog from "./delete-dialog.vue";

import moment from "moment";
import { useList } from "@/hooks/useList";
import {
  reqAgentRebateGrant,
  reqAgentRebateGrantBatch,
  reqAgentRebateList,
  reqAgentRebateReject
} from "@/api/report";
import { disableFutureDates, getDateArray } from "@/utils/common";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { usePremsStore } from "@/store/modules/prems";

interface TableItem {
  row: ReportAgentRebateMo;
}

const form = reactive({
  name: "",
  date: getDateArray()["today"]
});
const premsStore = usePremsStore();
const currentData = ref<ReportAgentRebateMo | null>(null);
const rebateDetailDialogRef = ref();
const deleteDialogRef = ref();

const getParams = () => {
  const params: any = {
    StartDate: moment(form.date[0]).format("YYYY-MM-DD 00:00:00"),
    EndDate: moment(form.date[1]).format("YYYY-MM-DD 23:59:59")
  };
  if (form.name) {
    params.Name = form.name;
  }
  return params;
};
const { elTableRef, state, list, getData, search } = useList<ReportAgentRebateMo, any>(
  reqAgentRebateList,
  getParams
);

// 重置
const handleRefresh = () => {
  form.name = "";
  form.date = getDateArray()["today"];
  search();
};

// 旗下详情
const handleOpenDetail = (row: ReportAgentRebateMo) => {
  currentData.value = row;
  nextTick(() => {
    rebateDetailDialogRef.value?.open();
  });
};

// 发放/拒绝
const handleAction = (row: ReportAgentRebateMo, type: 1 | 2 = 1) => {
  // 弹框操作
  ElMessageBox.confirm(`是否进行【${type == 1 ? "返佣" : "拒绝"}】操作`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          if (type == 1) {
            await reqAgentRebateGrant(row.UserId);
          } else {
            await reqAgentRebateReject(row.UserId);
          }
          if (type == 1) {
            message.success("一键返佣成功");
          } else {
            message.success("拒绝返佣成功");
          }
          getData();
          done();
          instance.confirmButtonLoading = false;
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

const handleDel = () => {
  deleteDialogRef.value?.open();
};

const handleBarch = () => {
  // 弹框操作
  ElMessageBox.confirm(`是否进行【批量返佣】操作`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await reqAgentRebateGrantBatch();
          getData();
          done();
          message.success("批量返佣成功");
          instance.confirmButtonLoading = false;
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

onMounted(() => {
  getData();
});
</script>
